package cre.tomcat7.ch02;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.util.Locale;

import static cre.tomcat7.ch02.Constant.SUCCESS_RESPONSE_LINE;
import static cre.tomcat7.ch02.Constant.WEB_APP;

/**
 * @Author penglai
 * @Date 2016/12/29.
 */
public class Response implements ServletResponse{
    private OutputStream outputStream;
    private PrintWriter writer;
    private Request request;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() {
        String fileName = request.getUri();
        FileInputStream fis = null;
        try {
            File file = new File(WEB_APP, fileName);

            if (file.exists()) {
                outputStream.write(SUCCESS_RESPONSE_LINE.getBytes());
                fis = new FileInputStream(file);
                byte[] bytes = new byte[1024];

                int i = fis.read(bytes, 0, 1024);
                while (i != -1) {
                    outputStream.write(bytes, 0, i);
                    i = fis.read(bytes, 0, 1024);
                }
            } else {
                String notFound = "HTTP/1.1 404 File Not Found\r\n" +
                        "Content-Type: text/html\r\n" +
                        "Content-Length: 23\r\n" +
                        "\r\n" +
                        "<h1>File Not Found</h1>";
                outputStream.write(notFound.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getCharacterEncoding() {
        return null;
    }

    public String getContentType() {
        return null;
    }

    public ServletOutputStream getOutputStream() throws IOException {
        return null;
    }

    public PrintWriter getWriter() throws IOException {
        writer = new PrintWriter(outputStream, true);
        return writer;
    }

    public void setCharacterEncoding(String charset) {

    }

    public void setContentLength(int len) {

    }

    public void setContentType(String type) {

    }

    public void setBufferSize(int size) {

    }

    public int getBufferSize() {
        return 0;
    }

    public void flushBuffer() throws IOException {

    }

    public void resetBuffer() {

    }

    public boolean isCommitted() {
        return false;
    }

    public void reset() {

    }

    public void setLocale(Locale loc) {

    }

    public Locale getLocale() {
        return null;
    }
}
